package com.study.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;

import com.study.config.CommonException;
import com.study.model.pojo.configPojo.ResultCode;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

@ConfigurationProperties("jwt.config")
public class JwtUtils {
    //签名私钥
    private String key = "xiaotang";
    //签名的失效时间
    private Long ttl = 3600000l;

    
    public String getKey() {
      return key;
    }


    public void setKey(String key) {
      this.key = key;
    }


    public Long getTtl() {
      return ttl;
    }


    public void setTtl(Long ttl) {
      this.ttl = ttl;
    }


    /**
     * 设置认证token
     *      id:登录用户id
     *      subject：登录用户名
     *
     */
    public String createJwt(String id, String name, Map<String,Object> map) {
        //1.设置失效时间
        long now = System.currentTimeMillis();//当前毫秒
        long exp = now + ttl;
        //2.创建jwtBuilder
        JwtBuilder jwtBuilder = Jwts.builder().setId(id).setSubject(name)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, key);
        //3.根据map设置claims
        for(Map.Entry<String,Object> entry : map.entrySet()) {
            jwtBuilder.claim(entry.getKey(),entry.getValue());
        }
        jwtBuilder.setExpiration(new Date(exp));
        //4.创建token
        String token = jwtBuilder.compact();
        return token;
    }


    /**
     * 解析token字符串获取clamis
     */
    public Claims parseJwt(String token) {
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        return claims;
    }
    
    
    /**解析后返回登陆者的id
     * @param request
     * @return
     * @throws Exception
     */
    public String getEmpid(HttpServletRequest request) throws Exception {
    //1.获取请求头信息：名称=Authorization
      String authorization = request.getHeader("Authorization");

      if (StringUtils.isEmpty(authorization)) {
        throw new CommonException(ResultCode.UNAUTHENTICATED);
      }
      //2.替换Bearer+空格
      String token = authorization.replace("Bearer ", "");
      
      //3.解析token
      Claims claims = this.parseJwt(token);
      String empid = claims.getId();
      return empid;
    }
}
